using DaoHang.Data;
using DaoHang.Models;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;

namespace DaoHang.Services
{
    /// <summary>
    /// 数据导出服务实现类
    /// </summary>
    public class DataExportService : IDataExportService
    {
        private readonly ApplicationDbContext context;
        private readonly ILogger<DataExportService> logger;
        private readonly IWebsiteService websiteService;
        private readonly ICategoryService categoryService;
        private readonly ISiteSettingsService siteSettingsService;
        private readonly ILogService logService;
        private readonly IUserService userService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="websiteService">网站服务</param>
        /// <param name="categoryService">分类服务</param>
        /// <param name="siteSettingsService">站点设置服务</param>
        /// <param name="logService">日志服务</param>
        /// <param name="userService">用户服务</param>
        public DataExportService(
            ApplicationDbContext context,
            ILogger<DataExportService> logger,
            IWebsiteService websiteService,
            ICategoryService categoryService,
            ISiteSettingsService siteSettingsService,
            ILogService logService,
            IUserService userService)
        {
            this.context = context;
            this.logger = logger;
            this.websiteService = websiteService;
            this.categoryService = categoryService;
            this.siteSettingsService = siteSettingsService;
            this.logService = logService;
            this.userService = userService;
        }

        /// <summary>
        /// 导出所有数据为JSON格式
        /// </summary>
        /// <returns>JSON字符串</returns>
        public async Task<string> ExportAllDataAsync()
        {
            try
            {
                logger.LogInformation("开始导出所有数据");

                var exportData = new DataExportModel
                {
                    ExportTime = DateTime.Now,
                    Version = "2.0", // 升级版本号以支持新的数据类型
                    Websites = await ExportWebsitesAsync(),
                    Categories = await ExportCategoriesAsync(),
                    SiteSettings = await ExportSiteSettingsAsync(),
                    AIConfigs = await ExportAIConfigsAsync(),
                    SystemLogs = await ExportSystemLogsAsync(),
                    Users = await ExportUsersAsync()
                };

                var options = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                };

                var jsonString = JsonSerializer.Serialize(exportData, options);
                
                logger.LogInformation("数据导出成功，网站: {WebsiteCount}，分类: {CategoryCount}，AI配置: {AIConfigCount}，日志: {LogCount}，用户: {UserCount}", 
                    exportData.Websites.Count, exportData.Categories.Count, exportData.AIConfigs.Count, 
                    exportData.SystemLogs.Count, exportData.Users.Count);

                return jsonString;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "导出所有数据失败");
                throw;
            }
        }

        /// <summary>
        /// 导出网站数据
        /// </summary>
        /// <returns>网站数据列表</returns>
        public async Task<List<WebsiteExportData>> ExportWebsitesAsync()
        {
            try
            {
                var websites = await websiteService.GetAllWebsitesAsync();
                var categories = await categoryService.GetAllCategoriesAsync();
                var categoryDict = categories.ToDictionary(c => c.Id, c => c.Name);

                var exportData = websites.Select(w => new WebsiteExportData
                {
                    Name = w.Name,
                    Url = w.Url,
                    Description = w.Description ?? "",
                    IconUrl = w.IconUrl ?? "",
                    CategoryName = categoryDict.GetValueOrDefault(w.CategoryId, "未分类"),
                    SortOrder = w.SortOrder,
                    IsEnabled = true, // Website模型没有IsEnabled属性，默认为true
                    CreatedAt = w.CreateTime
                }).ToList();

                logger.LogInformation("导出网站数据成功，数量: {Count}", exportData.Count);
                return exportData;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "导出网站数据失败");
                return new List<WebsiteExportData>();
            }
        }

        /// <summary>
        /// 导出分类数据
        /// </summary>
        /// <returns>分类数据列表</returns>
        public async Task<List<CategoryExportData>> ExportCategoriesAsync()
        {
            try
            {
                var categories = await categoryService.GetAllCategoriesAsync();

                var exportData = categories.Select(c => new CategoryExportData
                {
                    Name = c.Name,
                    Description = c.Description ?? "",
                    Icon = "", // Category模型没有Icon属性，默认为空
                    SortOrder = c.SortOrder,
                    IsEnabled = true, // Category模型没有IsEnabled属性，默认为true
                    CreatedAt = c.CreateTime
                }).ToList();

                logger.LogInformation("导出分类数据成功，数量: {Count}", exportData.Count);
                return exportData;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "导出分类数据失败");
                return new List<CategoryExportData>();
            }
        }

        /// <summary>
        /// 导出站点设置数据
        /// </summary>
        /// <returns>站点设置数据</returns>
        public async Task<SiteSettingsExportData?> ExportSiteSettingsAsync()
        {
            try
            {
                var settings = await siteSettingsService.GetSiteSettingsAsync();
                if (settings == null)
                {
                    return null;
                }

                var exportData = new SiteSettingsExportData
                {
                    SiteTitle = "", // SiteSettings模型没有这些属性，使用默认值
                    SiteDescription = "",
                    SiteKeywords = "",
                    LogoUrl = "",
                    IcpInfo = settings.IcpNumber ?? "",
                    Copyright = settings.PoliceNumber ?? "",
                    ContactEmail = ""
                };

                logger.LogInformation("导出站点设置数据成功");
                return exportData;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "导出站点设置数据失败");
                return null;
            }
        }

        /// <summary>
        /// 导出AI配置数据
        /// </summary>
        /// <returns>AI配置数据列表</returns>
        public Task<List<AIConfigExportData>> ExportAIConfigsAsync()
        {
            try
            {
                // AI配置现在简化为只在SiteSettings中存储API密钥
                // 返回空列表，因为不再有独立的AI配置
                logger.LogInformation("AI配置已简化，返回空列表");
                return Task.FromResult(new List<AIConfigExportData>());
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "导出AI配置数据失败");
                return Task.FromResult(new List<AIConfigExportData>());
            }
        }

        /// <summary>
        /// 从JSON导入数据
        /// </summary>
        /// <param name="jsonData">JSON数据</param>
        /// <param name="overwriteExisting">是否覆盖现有数据</param>
        /// <returns>导入结果</returns>
        public async Task<(bool success, string message, int importedCount)> ImportDataFromJsonAsync(string jsonData, bool overwriteExisting = false)
        {
            try
            {
                logger.LogInformation("开始导入数据，覆盖模式: {OverwriteMode}", overwriteExisting);

                // 验证数据格式
                var validation = await ValidateImportDataAsync(jsonData);
                if (!validation.isValid || validation.data == null)
                {
                    return (false, validation.message, 0);
                }

                var importData = validation.data;
                var importedCount = 0;

                using var transaction = await context.Database.BeginTransactionAsync();
                try
                {
                    // 导入分类数据
                    if (importData.Categories?.Any() == true)
                    {
                        importedCount += await ImportCategoriesAsync(importData.Categories, overwriteExisting);
                    }

                    // 导入网站数据
                    if (importData.Websites?.Any() == true)
                    {
                        importedCount += await ImportWebsitesAsync(importData.Websites, overwriteExisting);
                    }

                    // 导入站点设置
                    if (importData.SiteSettings != null)
                    {
                        await ImportSiteSettingsAsync(importData.SiteSettings, overwriteExisting);
                        importedCount++;
                    }

                    // 导入AI配置
                    if (importData.AIConfigs?.Any() == true)
                    {
                        importedCount += await ImportAIConfigsAsync(importData.AIConfigs, overwriteExisting);
                    }

                    // 导入系统日志
                    if (importData.SystemLogs?.Any() == true)
                    {
                        importedCount += await ImportSystemLogsAsync(importData.SystemLogs, overwriteExisting);
                    }

                    // 导入用户数据
                    if (importData.Users?.Any() == true)
                    {
                        importedCount += await ImportUsersAsync(importData.Users, overwriteExisting);
                    }

                    await transaction.CommitAsync();
                    
                    logger.LogInformation("数据导入成功，总计: {Count} 项", importedCount);
                    return (true, "数据导入成功", importedCount);
                }
                catch (Exception ex)
                {
                    await transaction.RollbackAsync();
                    logger.LogError(ex, "数据导入失败，已回滚事务");
                    return (false, $"导入失败: {ex.Message}", 0);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "数据导入过程中发生错误");
                return (false, $"导入错误: {ex.Message}", 0);
            }
        }

        /// <summary>
        /// 验证导入数据格式
        /// </summary>
        /// <param name="jsonData">JSON数据</param>
        /// <returns>验证结果</returns>
        public Task<(bool isValid, string message, DataExportModel? data)> ValidateImportDataAsync(string jsonData)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(jsonData))
                {
                    return Task.FromResult<(bool, string, DataExportModel?)>((false, "JSON数据不能为空", null));
                }

                var options = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    PropertyNameCaseInsensitive = true
                };

                var data = JsonSerializer.Deserialize<DataExportModel>(jsonData, options);
                if (data == null)
                {
                    return Task.FromResult<(bool, string, DataExportModel?)>((false, "无法解析JSON数据", null));
                }

                // 验证版本兼容性
                if (string.IsNullOrEmpty(data.Version))
                {
                    return Task.FromResult<(bool, string, DataExportModel?)>((false, "缺少版本信息", null));
                }

                // 验证数据完整性
                var validationErrors = new List<string>();

                if (data.Websites?.Any() == true)
                {
                    var invalidWebsites = data.Websites.Where(w => string.IsNullOrEmpty(w.Name) || string.IsNullOrEmpty(w.Url)).Count();
                    if (invalidWebsites > 0)
                    {
                        validationErrors.Add($"发现 {invalidWebsites} 个无效的网站记录（缺少名称或URL）");
                    }
                }

                if (data.Categories?.Any() == true)
                {
                    var invalidCategories = data.Categories.Where(c => string.IsNullOrEmpty(c.Name)).Count();
                    if (invalidCategories > 0)
                    {
                        validationErrors.Add($"发现 {invalidCategories} 个无效的分类记录（缺少名称）");
                    }
                }

                if (validationErrors.Any())
                {
                    return Task.FromResult<(bool, string, DataExportModel?)>((false, string.Join("; ", validationErrors), null));
                }

                logger.LogInformation("数据验证成功，网站: {WebsiteCount}，分类: {CategoryCount}，AI配置: {AIConfigCount}，日志: {LogCount}，用户: {UserCount}",
                    data.Websites?.Count ?? 0, data.Categories?.Count ?? 0, data.AIConfigs?.Count ?? 0, 
                    data.SystemLogs?.Count ?? 0, data.Users?.Count ?? 0);

                return Task.FromResult<(bool, string, DataExportModel?)>((true, "数据格式验证通过", data));
            }
            catch (JsonException ex)
            {
                logger.LogError(ex, "JSON格式验证失败");
                return Task.FromResult<(bool, string, DataExportModel?)>((false, $"JSON格式错误: {ex.Message}", null));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "数据验证过程中发生错误");
                return Task.FromResult<(bool, string, DataExportModel?)>((false, $"验证错误: {ex.Message}", null));
            }
        }

        /// <summary>
        /// 获取导出数据统计
        /// </summary>
        /// <returns>数据统计</returns>
        public async Task<Dictionary<string, int>> GetExportStatisticsAsync()
        {
            try
            {
                var statistics = new Dictionary<string, int>
                {
                    ["网站数量"] = await context.Websites.CountAsync(),
                    ["分类数量"] = await context.Categories.CountAsync(),
                    ["AI配置数量"] = 0, // AI配置已简化，返回0
                    ["系统日志数量"] = await context.SystemLogs.CountAsync(),
                    ["用户数量"] = await context.Users.CountAsync()
                };

                logger.LogInformation("获取导出统计成功");
                return statistics;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取导出统计失败");
                return new Dictionary<string, int>();
            }
        }

        /// <summary>
        /// 导入分类数据
        /// </summary>
        /// <param name="categories">分类数据</param>
        /// <param name="overwriteExisting">是否覆盖现有数据</param>
        /// <returns>导入数量</returns>
        private async Task<int> ImportCategoriesAsync(List<CategoryExportData> categories, bool overwriteExisting)
        {
            var importedCount = 0;
            var existingCategories = await categoryService.GetAllCategoriesAsync();
            var existingDict = existingCategories.ToDictionary(c => c.Name, c => c);

            foreach (var categoryData in categories)
            {
                if (existingDict.ContainsKey(categoryData.Name))
                {
                    if (overwriteExisting)
                    {
                        var existing = existingDict[categoryData.Name];
                        existing.Description = categoryData.Description;
                        // Category模型没有Icon和IsEnabled属性，跳过这些字段
                        existing.SortOrder = categoryData.SortOrder;
                        
                        await categoryService.UpdateCategoryAsync(existing);
                        importedCount++;
                    }
                }
                else
                {
                    var newCategory = new Category
                    {
                        Name = categoryData.Name,
                        Description = categoryData.Description,
                        // Category模型没有Icon和IsEnabled属性，跳过这些字段
                        SortOrder = categoryData.SortOrder,
                        CreateTime = categoryData.CreatedAt
                    };

                    await categoryService.CreateCategoryAsync(newCategory);
                    importedCount++;
                }
            }

            return importedCount;
        }

        /// <summary>
        /// 导入网站数据
        /// </summary>
        /// <param name="websites">网站数据</param>
        /// <param name="overwriteExisting">是否覆盖现有数据</param>
        /// <returns>导入数量</returns>
        private async Task<int> ImportWebsitesAsync(List<WebsiteExportData> websites, bool overwriteExisting)
        {
            var importedCount = 0;
            var existingWebsites = await websiteService.GetAllWebsitesAsync();
            var existingDict = existingWebsites.ToDictionary(w => w.Url, w => w);
            
            var categories = await categoryService.GetAllCategoriesAsync();
            var categoryDict = categories.ToDictionary(c => c.Name, c => c.Id);

            foreach (var websiteData in websites)
            {
                var categoryId = categoryDict.GetValueOrDefault(websiteData.CategoryName, 1); // 默认分类ID

                if (existingDict.ContainsKey(websiteData.Url))
                {
                    if (overwriteExisting)
                    {
                        var existing = existingDict[websiteData.Url];
                        existing.Name = websiteData.Name;
                        existing.Description = websiteData.Description;
                        existing.IconUrl = websiteData.IconUrl;
                        existing.CategoryId = categoryId;
                        existing.SortOrder = websiteData.SortOrder;
                        // Website模型没有IsEnabled属性，跳过此字段
                        
                        await websiteService.UpdateWebsiteAsync(existing);
                        importedCount++;
                    }
                }
                else
                {
                    var newWebsite = new Website
                    {
                        Name = websiteData.Name,
                        Url = websiteData.Url,
                        Description = websiteData.Description,
                        IconUrl = websiteData.IconUrl,
                        CategoryId = categoryId,
                        SortOrder = websiteData.SortOrder,
                        // Website模型没有IsEnabled属性，跳过此字段
                        CreateTime = websiteData.CreatedAt
                    };

                    await websiteService.CreateWebsiteAsync(newWebsite);
                    importedCount++;
                }
            }

            return importedCount;
        }

        /// <summary>
        /// 导入站点设置
        /// </summary>
        /// <param name="settingsData">站点设置数据</param>
        /// <param name="overwriteExisting">是否覆盖现有数据</param>
        /// <returns>任务</returns>
        private async Task ImportSiteSettingsAsync(SiteSettingsExportData settingsData, bool overwriteExisting)
        {
            var existingSettings = await siteSettingsService.GetSiteSettingsAsync();
            
            if (existingSettings == null || overwriteExisting)
            {
                var settings = existingSettings ?? new SiteSettings();
                
                // SiteSettings模型只有IcpNumber和PoliceNumber属性
                settings.IcpNumber = settingsData.IcpInfo;
                settings.PoliceNumber = settingsData.Copyright;

                await siteSettingsService.SaveSiteSettingsAsync(settings);
            }
        }

        /// <summary>
        /// 导入AI配置数据
        /// </summary>
        /// <param name="configs">AI配置数据</param>
        /// <param name="overwriteExisting">是否覆盖现有数据</param>
        /// <returns>导入数量</returns>
        private Task<int> ImportAIConfigsAsync(List<AIConfigExportData> configs, bool overwriteExisting)
        {
            // AI配置已简化，跳过导入
            logger.LogInformation("AI配置已简化，跳过 {Count} 个AI配置的导入", configs.Count);
            return Task.FromResult(0);
        }

        /// <summary>
        /// 导出系统日志数据
        /// </summary>
        /// <returns>系统日志数据列表</returns>
        public async Task<List<SystemLogExportData>> ExportSystemLogsAsync()
        {
            try
            {
                // 获取最近30天的日志以避免导出数据过大
                var cutoffDate = DateTime.Now.AddDays(-30);
                var logs = await context.SystemLogs
                    .Where(l => l.CreateTime >= cutoffDate)
                    .OrderByDescending(l => l.CreateTime)
                    .Take(1000) // 限制最多1000条
                    .ToListAsync();

                var exportData = logs.Select(l => new SystemLogExportData
                {
                    Level = l.Level,
                    Category = l.Category,
                    Message = l.Message,
                    Exception = l.Exception,
                    UserId = l.UserId,
                    IpAddress = l.IpAddress,
                    UserAgent = l.UserAgent,
                    RequestPath = l.RequestPath,
                    AdditionalData = l.AdditionalData,
                    CreateTime = l.CreateTime
                }).ToList();

                logger.LogInformation("导出系统日志数据成功，数量: {Count}", exportData.Count);
                return exportData;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "导出系统日志数据失败");
                return new List<SystemLogExportData>();
            }
        }

        /// <summary>
        /// 导出用户数据
        /// </summary>
        /// <returns>用户数据列表</returns>
        public async Task<List<UserExportData>> ExportUsersAsync()
        {
            try
            {
                var users = await context.Users.ToListAsync();

                var exportData = users.Select(u => new UserExportData
                {
                    Username = u.Username,
                    PasswordHash = u.PasswordHash,
                    Email = u.Email,
                    IsAdmin = u.IsAdmin,
                    CreateTime = u.CreateTime
                }).ToList();

                logger.LogInformation("导出用户数据成功，数量: {Count}", exportData.Count);
                return exportData;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "导出用户数据失败");
                return new List<UserExportData>();
            }
        }

        /// <summary>
        /// 导入系统日志数据
        /// </summary>
        /// <param name="logs">日志数据</param>
        /// <param name="overwriteExisting">是否覆盖现有数据</param>
        /// <returns>导入数量</returns>
        private async Task<int> ImportSystemLogsAsync(List<SystemLogExportData> logs, bool overwriteExisting)
        {
            var importedCount = 0;

            try
            {
                if (overwriteExisting)
                {
                    // 如果覆盖现有数据，先清空现有日志
                    var existingLogs = await context.SystemLogs.ToListAsync();
                    context.SystemLogs.RemoveRange(existingLogs);
                    await context.SaveChangesAsync();
                }

                foreach (var logData in logs)
                {
                    var newLog = new SystemLog
                    {
                        Level = logData.Level,
                        Category = logData.Category,
                        Message = logData.Message,
                        Exception = logData.Exception,
                        UserId = logData.UserId,
                        IpAddress = logData.IpAddress,
                        UserAgent = logData.UserAgent,
                        RequestPath = logData.RequestPath,
                        AdditionalData = logData.AdditionalData,
                        CreateTime = logData.CreateTime
                    };

                    context.SystemLogs.Add(newLog);
                    importedCount++;
                }

                await context.SaveChangesAsync();
                logger.LogInformation("导入系统日志数据成功，数量: {Count}", importedCount);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "导入系统日志数据失败");
            }

            return importedCount;
        }

        /// <summary>
        /// 导入用户数据
        /// </summary>
        /// <param name="users">用户数据</param>
        /// <param name="overwriteExisting">是否覆盖现有数据</param>
        /// <returns>导入数量</returns>
        private async Task<int> ImportUsersAsync(List<UserExportData> users, bool overwriteExisting)
        {
            var importedCount = 0;

            try
            {
                var existingUsers = await context.Users.ToListAsync();
                var existingDict = existingUsers.ToDictionary(u => u.Username, u => u);

                foreach (var userData in users)
                {
                    if (existingDict.ContainsKey(userData.Username))
                    {
                        if (overwriteExisting)
                        {
                            var existing = existingDict[userData.Username];
                            existing.PasswordHash = userData.PasswordHash;
                            existing.Email = userData.Email;
                            existing.IsAdmin = userData.IsAdmin;
                            // 保持原有的CreateTime

                            importedCount++;
                        }
                    }
                    else
                    {
                        var newUser = new User
                        {
                            Username = userData.Username,
                            PasswordHash = userData.PasswordHash,
                            Email = userData.Email,
                            IsAdmin = userData.IsAdmin,
                            CreateTime = userData.CreateTime
                        };

                        context.Users.Add(newUser);
                        importedCount++;
                    }
                }

                await context.SaveChangesAsync();
                logger.LogInformation("导入用户数据成功，数量: {Count}", importedCount);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "导入用户数据失败");
            }

            return importedCount;
        }
    }
} 